package com.wtone.platform.gat.images.gat.interceptor;

import com.alibaba.fastjson.JSON;
import com.wtone.platform.gat.images.gat.config.BeanContext;
import com.wtone.platform.gat.images.gat.core.Constants;
import com.wtone.platform.gat.images.gat.entity.GatUser;
import com.wtone.platform.gat.images.gat.mapper.GatUserMapper;
import com.wtone.platform.gat.images.gat.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author: aiLin
 * @Date: 2020/10/12 11:17
 * @desc: 授权拦截器
 */
@Slf4j
@Configuration
public class AuthorityInterceptor implements HandlerInterceptor {

    private GatUserMapper gatUserMapper;

    private static final String deviceID = "44030520205039102815";

    private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI

    static {
        NOT_INTERCEPT_URI.add("/doc.html");
        NOT_INTERCEPT_URI.add("/favicon.ico");
    }

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object object) throws Exception {
        String uri = request.getRequestURI();
        if (NOT_INTERCEPT_URI.contains(uri)) {
            log.info("不拦截" + uri);
            return true;
        }
        //log.info("拦截" + uri);
        String header = request.getHeader(Constants.REQTOKEN);
        if(StringUtils.isEmpty(header)){
            throw new RuntimeException("视图库编号传入不能为空.");
        }
        if(!deviceID.equals(header)){
            throw new RuntimeException("User-Identify 视图库编号校验异常，请检查参数.");
        }
        //验证用户名
        String Authorization = request.getHeader("Authorization");
        if(Authorization.contains("Digest")){
            String digest = Authorization.replace("Digest", "{");
            digest+="}";
            log.info(digest);
            Object o = JSON.toJSONString(digest);
            String reuslt = String.valueOf(o);
            String str = "{ username=\"wtw_hk\", realm=\"wtone GAT1400\", nonce=\"MTYwMjY3MDIwMjk0NDo2OTI4MzU2MjdiNzM4ZGU4MzQyMmQ4NmI0NzE4YjNhMg==\", uri=\"/VIID/Images\", algorithm=\"MD5\", qop=auth, nc=00000001, cnonce=\"irDUsBKz\", response=\"e6810fb8f3b96ccd80ec1f8d6bc19797\"}";
            str = reuslt.replace(" ", "");
            str = str.substring(1,str.length()-1).replaceAll("\"","");
            Map map = new HashMap();
            String[] arr = str.split(",");
            for (String value:arr) {
                String key = value.substring(0,value.indexOf("=")).replace(" ", "");
                if(key.contains("{")){
                    key = key.replace("{","");
                }
                String val = value.substring(value.indexOf("=")+1);
                if(val.contains("\\")){
                    val = val.replace("\\","").replace("\\","");
                }
                map.put(key,val);
            }
            String username = String.valueOf(map.get("username"));
           /* String replace = digest.replace("", "");
            Object o = JSON.toJSONString(replace);
            String reuslt = String.valueOf(o);
            log.info(reuslt);
            reuslt = reuslt.substring(reuslt.indexOf("=")+3,reuslt.indexOf(",")-2);*/
            GatUser gatUser = new GatUser();
            gatUser.setUserName(username);
            GatUserMapper gatUserMapper = BeanContext.getApplicationContext().getBean(GatUserMapper.class);
            List<GatUser> gatUsers = gatUserMapper.selectGatUserList(gatUser);
            if(gatUsers==null || gatUsers.size()<=0){
                throw new RuntimeException("用户名或者密码错误.");
            }
        }
        return true;
    }


    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行
     * （主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
    }
}
